class Message < ActiveRecord::Base
  belongs_to :suser,
             :class_name => 'User',
             :foreign_key => 'sender_id'
  belongs_to :ruser,
             :class_name => 'User',
             :foreign_key => 'receiver_id' 
  attr_accessor :username 
  before_create :set_sender_id
  
  validates_presence_of :title,:content, :message => "不能为空"
  validate_on_create :valid_username?
  
  private
  def set_sender_id
    self.receiver_id = User.find_by_username(self.username).id
  end
  
  def valid_username?
    unless self.username && User.find_by_username(self.username)
      errors.add(:username,"不存在")
    end
  end
end
